

package com.hazelcast.internal.config.yaml;

import com.hazelcast.config.InvalidConfigurationException;
import com.hazelcast.internal.yaml.*;

import java.util.Set;

/**
 * Utility class for checking the provided YAML DOM for {@code null}
 * scalar values and mappings or sequences with {@code null} child nodes.
 */
public final class YamlDomChecker {

    private YamlDomChecker() {
    }

    /**
     * Performs {@code null} checks on the provided on YAML node recursively.
     * This check is skipped on the nodes defined as nullable.
     *
     * @param node          The YAML node to check for {@code null}s
     * @param nullableNodes The names of nodes on which null check is not performed
     */
    public static void check(YamlNode node, Set<String> nullableNodes) {
        if (node instanceof YamlMapping mapping) {
            for (YamlNameNodePair nodePair : mapping.childrenPairs()) {
                YamlNode child = nodePair.childNode();
                if (child == null) {
                    if (nullableNodes.contains(nodePair.nodeName())) {
                        return;
                    }
                    String path = YamlUtil.constructPath(node, nodePair.nodeName());
                    reportNullEntryOnConcretePath(path);
                }
                check(child, nullableNodes);
            }
        } else
            if (node instanceof YamlSequence sequence) {
                for (YamlNode child : sequence.children()) {
                    if (child == null) {
                        throw new InvalidConfigurationException("There is a null configuration entry under sequence " + node.path() + ". Please check if the provided YAML configuration is well-indented and no blocks started without " + "sub-nodes.");
                    }
                    check(child, nullableNodes);
                }
            } else {
                if (((YamlScalar) node).nodeValue() == null) {
                    reportNullEntryOnConcretePath(node.path());
                }
            }
    }

    private static void reportNullEntryOnConcretePath(String path) {
        throw new InvalidConfigurationException("The configuration entry under " + path + " is null. Please check if the provided YAML configuration is well-indented and no blocks started" + " without sub-nodes.");
    }
}
